<template>
  <div v-title>
    <div id="map-container">
    </div>
    <el-input v-model="searchMarkerText" class="searchSuggestInput" placeholder="请输入手机号或家庭名称"
              clearable
    ></el-input>
    <div class="rightPanelStyle">
      <el-table :data="paginatedList" border @row-click="selectOneHome" :max-height="tableMaxHeight">
        <el-table-column label="手机号" prop="account" width="120">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top-start">
              <div style="width: 300px">
                <el-descriptions :column="1">
                  <el-descriptions-item label="手机号">{{ scope.row.account }}</el-descriptions-item>
                  <el-descriptions-item label="昵称">{{ scope.row.nickName }}</el-descriptions-item>
                  <el-descriptions-item label="所属组织">{{ scope.row.deptName }}</el-descriptions-item>
                </el-descriptions>
              </div>
              <span slot="reference">
                  {{ scope.row.account }}
                </span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="家庭名称" prop="homeName" width="250"></el-table-column>
      </el-table>
      <el-pagination
        v-show="filterHomeListSize>0"
        :total="filterHomeListSize"
        layout="total,prev,next,jumper"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @current-change="handleCurrentPageChange"
      />
    </div>
  </div>
</template>

<script>
import { listHomePositionAndUser } from '@/api/system/home'

export default {
  name: 'index',
  data() {
    return {
      total: 0,
      allHomePositionList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        homeName: undefined,
        account: undefined,
        nickName: undefined
      },
      locationMap: null,
      markers: [],
      center: [],
      selectedHomeId: null,
      searchMarkerText: '',
      tableMaxHeight: window.innerHeight * 0.7
    }
  },
  created() {
    this.initMap()
    this.getList()
  },
  mounted() {
    // 浏览器页面大小发送变化时修改table的max-height
    window.onresize = () => {
      return (() => {
        this.tableMaxHeight = window.innerHeight * 0.7
      })()
    }
  },
  computed: {
    /**
     * 筛选出有地理位置的家庭
     */
    locatedHome() {
      return this.allHomePositionList.filter(item => {
        return item.longitude != null
      })
    },
    /**
     * 过滤后的用户列表(未分页), 按家庭名称和手机号查询
     */
    filterHomeList() {
      return this.locatedHome.filter(item => {
        return item.account.indexOf(this.searchMarkerText) !== -1 || item.homeName.indexOf(this.searchMarkerText) !== -1
      })
    },
    /**
     * 过滤后列表项的数量
     */
    filterHomeListSize() {
      return this.filterHomeList.length
    },
    /**
     * 分页后的列表数据
     */
    paginatedList() {
      let startIndex = (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      let endIndex = (this.queryParams.pageNum) * this.queryParams.pageSize
      return this.filterHomeList.filter((item, index) => {
        return index >= startIndex && index < endIndex
      })
    }
  },
  methods: {
    /** 查询家庭列表 */
    getList() {
      listHomePositionAndUser(this.queryParams).then(response => {
        this.allHomePositionList = response.rows
        this.total = response.total
      })
    },
    /** 初始化地图, 创建并挂载, 添加当前位置的标记  */
    initMap() {
      let self = this
      AMap.plugin('AMap.Geolocation', function() {
        let geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 5000
        })

        geolocation.getCurrentPosition()
        AMap.event.addListener(geolocation, 'complete', onComplete)
        AMap.event.addListener(geolocation, 'error', onError)

        // 定位查询成功回调, data是具体的定位信息
        function onComplete(data) {
          // 挂在地图到容器, 中心点为查询的地址（web端根据ip查询）
          self.locationMap = new AMap.Map('map-container', {
            resizeEnable: true, //是否监控地图容器尺寸变化
            zoom: 7, //初始化地图层级, 默认省级
            center: [data.position.lng, data.position.lat] //初始化地图中心点
          })
          self.center = [data.position.lng, data.position.lat]
          self.addInitComponent(self)
          self.createMarkerCluster()
        }

        // 定位出错
        function onError(data) {
          console.log('定位出错了!!')
          self.locationMap = new AMap.Map('map-container', {
            resizeEnable: true, //是否监控地图容器尺寸变化
            zoom: 7, //初始化地图层级
            center: [120.028666000000000, 30.241042000000000] //初始化地图中心点
          })
          self.center = [120.028666000000000, 30.241042000000000]
          self.addInitComponent(self)
          self.createMarkerCluster()
        }
      })
    }, /**
     * 给地图添加当前位置的标记, 工具条, 比例尺, 方向盘
     */
    addInitComponent(vueInstance) {
      // 加载工具条, 比例尺, 方向盘
      AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.ControlBar'], function() {
        let toolbar = new AMap.ToolBar()
        let scale = new AMap.Scale()

        vueInstance.locationMap.addControl(toolbar)
        vueInstance.locationMap.addControl(scale)
      })
    },
    /**
     * 渲染markers, 根据this.allUserPositionList中的数据生成marker进行添加
     * 标记设置鼠标移入、移出的时间, 使用点聚合
     */
    createMarkerCluster() {
      listHomePositionAndUser({ pageNum: 1 }).then(response => {
        this.allHomePositionList = response.rows
        // 渲染markers
        // 遍历allUserPositionList, 每次生成一个marker
        if (this.locationMap) {
          let markers = []
          let self = this
          for (let value of this.locatedHome) {
            let markerLabelContent = `<div class="markerLabelTextContainer">${value.homeName}</div>`
            let markerContent = `<div class="custom-content-marker"><img src="https://www.img.zyzncloud.com/UserHeadImg/default.jpg" alt=""/></div>`

            // 设置显示顺序
            let zIndex = value.account === this.selectedAccount ? 1 : -1

            // 生成marker
            let marker = new AMap.Marker({
              position: [value.longitude, value.latitude],
              content: markerContent,
              label: {
                content: markerLabelContent,
                offset: new AMap.Pixel(0, 21),
                direction: 'center'
              },
              // content: markerContent,
              extData: { homeId: value.homeId },
              zIndex: zIndex
            })

            markers.push(marker)

            // marker添加鼠标移入事件, 显示信息窗体
            let infoWindowContent = []
            infoWindowContent.push(`<div style="background-color: white; width: 100%">`)
            infoWindowContent.push(`<div class="infoWindow-Title">${value.position}</div>`)
            infoWindowContent.push(`<div class="link-top"></div>`)
            // markerContent.push(`<img src="${value.imgUrl}" width="100px" height="100px"/> <br/>`)
            infoWindowContent.push(`<div class="infoWindow-Content">【手机号】${value.account}</div>`)
            infoWindowContent.push(`<div class="infoWindow-Content2">【家庭名称】${value.homeName}</div>`)
            infoWindowContent.push(`</div>`)
            AMap.event.addListener(marker, 'mouseover', function() {
              let infoWindow = new AMap.InfoWindow({
                isCustom: true,
                content: infoWindowContent.join(''),
                offset: new AMap.Pixel(16, -50)
              })

              infoWindow.open(self.locationMap, marker.getPosition())
            })

            // marker添加鼠标移出事件, 清楚信息窗体
            AMap.event.addListener(marker, 'mouseout', function() {
              self.locationMap.clearInfoWindow()
            })
          }

          this.markers = markers
          this.locationMap.clearInfoWindow()
          // 点聚合
          if (this.cluster) {
            //非第一次渲染
            this.cluster.setMarkers(markers)
          } else {
            //第一次渲染
            this.cluster = new AMap.MarkerClusterer(this.locationMap, this.markers, {
              gridSize: 80,
              maxZoom: 11 //点聚合等级为市
            })
          }
        }
      })
    },
    /**
     * 点击列表项
     */
    selectOneHome(event) {
      let selectedLongitude = event.longitude
      let selectedLatitude = event.latitude
      let selectedHomeId = event.homeId
      this.locationMap.setZoomAndCenter(18, [selectedLongitude, selectedLatitude])

      // // 遍历markers, 将选中的marker的zIndex设置为1, 其余的为-1, 并获取选中的marker
      let selectedMarker
      for (let i = 0, len = this.markers.length; i < len; i++) {
        if (this.markers[i].getExtData().homeId === selectedHomeId) {
          selectedMarker = this.markers[i]
          this.markers[i].setzIndex(1)
        } else {
          this.markers[i].setzIndex(-1)
        }
      }

      if (selectedMarker) {
        this.cluster.setMarkers(this.markers)
        selectedMarker.setAnimation('AMAP_ANIMATION_DROP')
      }
    },
    handleCurrentPageChange(currentPage) {
      this.queryParams.pageNum = currentPage
    }
  }
}
</script>

<style scoped>
#map-container {
  width: calc(80vw);
  height: calc(100vh);
  float: left;
}

.rightPanelStyle {
  float: left;
  width: 15%;
  margin-top: calc(1vh);
  margin-left: calc(1vw);
}

.searchSuggestInput {
  width: 15%;
  margin-top: 2vh;
  margin-left: 1vw;
}
</style>
